#ifndef _HLFS_MISC_H_
#define _HLFS_MISC_H_

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
#include <fcntl.h>
//#include "hlfs.h"
#include "address.h"

static uint64_t get_current_time(void)
{
	struct timeval t;

	if (gettimeofday(&t, NULL)) {
		g_message("Get current time error!\n");
		return -1;
	}
	return (uint64_t) t.tv_sec * 1000 + t.tv_usec / 1000;	
}

static char *build_segfile_name(uint64_t segno)
{
    	char s[64];
    	sprintf(s, "%llu", segno);
    	gchar * segfile_name = g_strconcat(s, ".", "seg", NULL);
    	return segfile_name;
}

static char *build_segfile_name_by_address(uint64_t storage_address)
{
	uint32_t segno  = get_segno(storage_address);
    	char s[64];
    	sprintf(s, "%d", segno);
    	gchar * segfile_name = g_strconcat(s,".","seg",NULL);
    	return segfile_name;
}

static char *read_block(void *storage_handler ,uint64_t storage_address,uint32_t block_size)
{
	int ret = 0;
    	uint32_t offset = get_offset(storage_address); 
    	gchar * segfile_name = build_segfile_name(get_segno(storage_address));
    	gchar * path = (gchar *)storage_handler;
    	gchar * segfile_path = g_build_filename(path,segfile_name,NULL);
	char * block = (char*)g_malloc0(block_size);
    	if (!block) {
	    	g_message("%s -- allocate error!\n", __func__);
	    	return NULL;
    	}
    	int fd = open(segfile_path,O_RDONLY);
    	if (fd ==-1) {
        	ret = -1;
        	g_free(block);
        	block = NULL;
        	goto out2;
    	}
    	if(block_size != pread(fd,block,block_size,offset)){
        	ret = -1;
        	g_free(block);
        	block = NULL;
        	goto out1;
    	}
out1:
    	close(fd);
out2:
    	g_free(segfile_name);
    	g_free(segfile_path);
    	return block;
}

#endif 
